package com.geek.jdbc.pool.custom;

import com.geek.jdbc.utils.JDBCUtils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;

/**
 * @Desc TODO
 * @Author
 * @Date 2025/11/17
 *
 * 数据库连接池的优点
 * 1.资源重用
 * 2.更快的系统反应速度
 * 3.新的资源分配手段
 * 4.统一的连接管理，避免数据库连接泄露
 *
 * 自定义的数据库连接池
 * 1.实现数据源 implements DataSource
 * 2.定义容器LinkedList<Connection>，存储连接对象 --> 基于链表的数据结构，操作分头分尾
 * 3.获取连接 removeFirst()
 * 4.归还连接 addLast()
 */
public class MyDataSource implements DataSource {

    //数据库连接池
    private LinkedList<Connection> pool;

    public MyDataSource() {
        pool = new LinkedList<>();
        //预定义5个连接对象存储至容器中
        for (int i = 0; i < 5; i++) {
            pool.add(JDBCUtils.getConn());
        }
    }

    //关闭方法,讲连接对象归还至连接池中
    public void close(Connection conn){
        pool.addLast(conn);
    }

    //获取连接方法
    @Override
    public Connection getConnection() throws SQLException {
        Connection conn = pool.removeFirst();
        return conn;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
